<template>
	<el-form inline class="toolbar-wrap" :model="tool">
		<el-form-item label="线条拖拽工具">
			<el-switch v-model="tool.draw" @change="changeDraw" />
		</el-form-item>
		<el-form-item label="对齐线">
			<el-switch v-model="tool.snapline" @change="changeSnapLine" />
		</el-form-item>
		<el-form-item>
			<el-dropdown type="primary">
				<el-button type="primary">图形操作</el-button>
				<template #dropdown>
					<el-dropdown-menu>
						<el-dropdown-item @click="save">
							<span style="font-size: 16px">保存数据</span>
						</el-dropdown-item>
						<el-dropdown-item @click="copy">
							<span style="font-size: 16px">复制</span>
						</el-dropdown-item>
						<el-dropdown-item @click="paset">
							<span style="font-size: 16px">粘贴</span>
						</el-dropdown-item>
						<el-dropdown-item @click="remove">
							<span style="font-size: 16px">删除</span>
						</el-dropdown-item>
					</el-dropdown-menu>
				</template>
			</el-dropdown>
		</el-form-item>
	</el-form>
</template>

<script lang="ts" setup>
import { inject, reactive } from "vue";
import { ElMessage } from "element-plus";
import { FlowGraphContextKey } from "@/utils/flow-graph";
import type { EdgeView } from "@antv/x6";

interface ToolData {
	draw: boolean;
	snapline: boolean;
	currentPlanId: number | null;
}

const context = inject(FlowGraphContextKey)!;

const tool = reactive<ToolData>({ draw: false, snapline: true, currentPlanId: null });

let saveData: any;

const copy = () => {
	saveData = context.graph.toJSON();
	ElMessage.success("复制成功");
};
const paset = () => saveData && context.graph.fromJSON(saveData);
const remove = () => context.graph.clearCells();

/** 对齐线 */
const changeSnapLine = () => {
	context.graph.isSnaplineEnabled()
		? context.graph.disableSnapline()
		: context.graph.enableSnapline();
};

/** 线条拖拽工具添加或删除 */
const handler: (e: EdgeView) => void = ({ cell }) => {
	cell.addTools("vertices", "onhover");
	cell.addTools([
		"source-arrowhead",
		{
			name: "target-arrowhead",
			args: { attrs: { fill: "red" } }
		}
	]);
};

/** 线条拖拽工具事件注册 */
const changeDraw = (val: string | number | boolean) => {
	const { graph } = context;
	if (val) {
		graph.off("edge:mouseenter", handler);
		graph.on("edge:mouseenter", handler);
	} else {
		graph.off("edge:mouseenter", handler);
	}
};

/** 保存数据 */
const save = async () => {
	localStorage.setItem("flow", JSON.stringify(context.graph.toJSON()));
	ElMessage.success("保存成功");
};
</script>

<style lang="scss" scoped>
.toolbar-wrap {
	padding-left: 10px;
	height: 38px;
	display: flex;
	align-items: center;
	border-top: 1px solid rgba(0, 0, 0, 0.08);
	box-sizing: border-box;
	:deep(.el-form-item) {
		margin-bottom: 0;
		margin-right: 20px;
	}
}
</style>
